package com.example.personal.aiagent.common.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.example.personal.aiagent.common.constant.ErrorCode;
import com.example.personal.aiagent.common.exception.CustomServiceException;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户工具类
 */
@Slf4j
public class UserUtil {
    public static String getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                return ((UserDetails) principal).getUsername();
            } else {
                log.error("principal not UserDetails");
                throw new CustomServiceException(ErrorCode.UNKNOWN_USER);
            }
        } else {
            log.error("user unauthenticated");
            throw new CustomServiceException(ErrorCode.UNKNOWN_USER);
        }
    }
}
